package MTT::Controller::Ajax;
use Moose;
use namespace::autoclean;

BEGIN {extends 'Catalyst::Controller'; }

=head1 NAME

MTT::Controller::Ajax - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut

use utf8;

use Data::Dumper;
use Time::HiRes qw(gettimeofday tv_interval);
use MTT::Libs::ReportData;

sub masks : Path('/ajax/masks') {
	my ($self, $c) = @_;

	my $name = $c->req->params->{name};
	my $vals = $c->req->params->{'vals[]'};
	$vals = [ $vals ] unless ref $vals;

	my %params = (
		mask 	  => 'mask',
		mcountry  => 'country',
		marea 	  => 'area',
		mregion   => 'region',
		mcity	  => 'city',
		moperator => 'operator'
	);


	my $all = $vals->[0] eq 'all' ? 1 : 0;

	my $masks = $self->get_masks($c, (!$all ? ($params{$name}, $vals) : ()));

	$c->stash->{json_data} = {
		mask 	  => $masks->{mask},
		mcountry  => $masks->{country},
		marea 	  => $masks->{area},
		mregion   => $masks->{region},
		mcity 	  => $masks->{city},
		moperator => $masks->{operator},
		selected  => $name
	};

	$c->component('View::JSON')->encoding('utf-8');
	$c->forward('View::JSON');
}

sub get_masks {
	my ($self, $c, $key, $value) = @_;

	my $masks = {};
	if ( $value ) {
		$value = [ $value ] unless ref $value;
	}
	my @cond = $key ? ( $key, {IN => $value} ) : ();
	my (@mask, @country, @area, @region, @city, @operator);

	my $rs = $c->model('DBIC::Mask')->search({@cond}, {columns => 'mask'});
	$rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
	foreach my $m ( $rs->all() ) {
		push @mask, $m->{mask} if $m->{mask};
	}

	$rs = $c->model('DBIC::Mask')->search({@cond}, {columns => 'country', distinct => 1});
	$rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
	foreach my $m ( $rs->all() ) {
		push @country, $m->{country} if $m->{country};
	}

	$rs = $c->model('DBIC::Mask')->search({@cond}, {columns => 'area', distinct => 1});
	$rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
	foreach my $m ( $rs->all() ) {
		push @area, $m->{area} if $m->{area};
	}

	$rs = $c->model('DBIC::Mask')->search({@cond}, {columns => 'region', distinct => 1});
	$rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
	foreach my $m ( $rs->all() ) {
		push @region, $m->{region} if $m->{region};
	}

	$rs = $c->model('DBIC::Mask')->search({@cond}, {columns => 'city', distinct => 1});
	$rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
	foreach my $m ( $rs->all() ) {
		push @city, $m->{city} if $m->{city};
	}

	$rs = $c->model('DBIC::Mask')->search({@cond}, {columns => 'operator', distinct => 1});
	$rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
	foreach my $m ( $rs->all() ) {
		push @operator, $m->{operator} if $m->{operator};
	}

	return {
		mask => \@mask,
		country => \@country,
		area 	=> \@area,
		region 	=> \@region,
		city	=> \@city,
		operator => \@operator
	}

}

sub trunks_search: Path('/ajax/trunks_search') {
	my ($self, $c) = @_;
	
	my $field = $c->req->params->{field};
	my $val  = '%' . $c->req->params->{'val'} . '%';

	my $rs = $c->model('DBIC::Trunk')->search({
			$field  => { 'LIKE' => $val },
			created => { '>=' => \'DATE(NOW())' }
		},
		{
			columns => $field
		}
	);

	$rs->result_class('DBIx::Class::ResultClass::HashRefInflator');

	my %result;
	while ( my $row = $rs->next() ) {
		$result{ $row->{$field} }++;
	}

	my @result;
	if ( $field eq 'trunk' ) {
		@result = map { [ $_ => $_ ] } 
			sort { 
				my $ad = $a =~ /^\d+$/;
				my $bd = $b =~ /^\d+$/;
				my ($aip) = $a =~ /^(\d+)\./;
				my ($bip) = $b =~ /^(\d+)\./;

				$ad && !$bd ? -1 :
				$bd && !$ad ?  1 :
				$ad && $bd ? $a <=> $b :
				$aip && !$bip ? -1 :
				$bip && !$aip ?  1 :
				$aip && $bip ? $aip <=> $bip :
				$a cmp $b
			} keys %result;
	}
	else {
		@result = map { [ $_ => $_ ] } sort keys %result;
	}

	$c->stash->{json_data} = {
		result  => \@result,
	};

	$c->component('View::JSON')->encoding('utf-8');
	$c->forward('View::JSON');
}

sub trunks_select: Path('/ajax/trunks_select') {
	my ($self, $c) = @_;
	
	my $field = $c->req->params->{field};
	my $type  = $c->req->params->{type};
	my $vals  = $c->req->params->{'vals[]'};

	my $rs = $c->model('DBIC::Trunk')->search({
			$field  => { 'IN' => $vals },
			created => { '>=' => \'DATE(NOW())' }
		},
		{
			columns => [ qw(switch trunk company_name) ]
		}
	);

	$rs->result_class('DBIx::Class::ResultClass::HashRefInflator');

	my ( %switches, %trunks, %companies );
	while ( my $row = $rs->next() ) {
		$switches{ $row->{switch} }++;
		$trunks{ $row->{trunk} }++;
		$companies{ $row->{company_name} }++;
	}

	my ( @switches, @trunks, @companies );

	my $st = MTT::Libs::ReportData->instance->switches_for_search();
	@switches  = map { [ $_ => $st->{$_} ] } sort keys %switches;
	@companies = map { [ $_ => $_ ] } sort keys %companies;
	@trunks = map { [ $_ => $_ ] } 
		sort { 
			my $ad = $a =~ /^\d+$/;
			my $bd = $b =~ /^\d+$/;
			my ($aip) = $a =~ /^(\d+)\./;
			my ($bip) = $b =~ /^(\d+)\./;

			$ad && !$bd ? -1 :
			$bd && !$ad ?  1 :
			$ad && $bd ? $a <=> $b :
			$aip && !$bip ? -1 :
			$bip && !$aip ?  1 :
			$aip && $bip ? $aip <=> $bip :
			$a cmp $b
		} keys %trunks;

	$c->stash->{json_data} = {
		switches  => \@switches,
		trunks	  => \@trunks,
		companies => \@companies
	};

	$c->component('View::JSON')->encoding('utf-8');
	$c->forward('View::JSON');

}


sub trunks: Path('/ajax/trunks') {
	my ($self, $c) = @_;

	my $name = $c->req->params->{name};
	my $vals = $c->req->params->{'vals[]'};
	$vals = [ $vals ] unless ref $vals;

	my (@switches, @switch_types, @companies, @cities, @obls, @fos, @trunks);
	my (%switch_types, %companies, %cities, %obls, %fos, %trunks);
	my %host_code;
	my $rs;

	my $selected = '';

	my $is_all = $vals->[0] =~ /^0$/;

	if ( $is_all ) {
		$rs = $c->model('DBIC::Trunk')->search({
				created => { '>=' => \'DATE(NOW())' }
		}); 
		foreach my $switch ( $c->model('DBIC::Switch')->all() ) {
			push @switches, {
				id => $switch->id, 
				name => $switch->descr
			} unless $host_code{ $switch->host_code }++;
			push @switch_types, {
				id => $switch->id_type->id, 
				type => $switch->id_type->type
			};
		}
	}
	else {
		if ( $name eq 'companies' ) {
			$rs = $c->model('DBIC::Trunk')->search({
					company_name => { 'IN' => $vals }, 
					created => { '>=' => \'DATE(NOW())' } 
			}); 
			$selected = 'companies';
		}
		elsif ( $name eq 'cities' ) {
			$rs = $c->model('DBIC::Trunk')->search({
					city => { 'IN' => $vals }, 
					created => { '>=' => \'DATE(NOW())' } 
			}); 
			$selected = 'cities';
		}
		elsif ( $name eq 'obls' ) {
			$rs = $c->model('DBIC::Trunk')->search({
					oblast => { 'IN' => $vals }, 
					created => { '>=' => \'DATE(NOW())' } 
			}); 
			$selected = 'obls';
		}
		elsif ( $name eq 'fos' ) {
			$rs = $c->model('DBIC::Trunk')->search({
					fo => { 'IN' => $vals }, 
					created => { '>=' => \'DATE(NOW())' } 
			}); 
			$selected = 'fos';
		}
		elsif ( $name eq 'trunks' ) {
			$rs = $c->model('DBIC::Trunk')->search({
					trunk => { 'IN' => $vals }, 
					created => { '>=' => \'DATE(NOW())' } 
			}); 
			$selected = 'trunks';
		}
		elsif ( $name eq 'switches_do' ) { 
			my @sws;
			foreach ( @$vals ) {
				my $sw = $c->model('DBIC::Switch')->find($_);
				push @sws, $sw->host_code if $sw;
			}

			$rs = $c->model('DBIC::Trunk')->search({
					switch => { 'IN' => \@sws }, 
					created => { '>=' => \'DATE(NOW())' } 
			}); 
			$selected = 'switch';
		}
	}

	$rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
	while ( my $trunk = $rs->next() ) {
		unless ( $is_all ) { 
			my $sws = $c->model('DBIC::Switch')->search({host_code => $trunk->{switch}});
			if ( my $switch = $sws->next ) {
				push @switches, {
					id => $switch->id, 
					name => $switch->descr
				} unless $host_code{ $switch->host_code }++;
				push @switch_types, {
					id => $switch->id_type->id, 
					type => $switch->id_type->type
				};
			}	
		}

		push @companies, $trunk->{company_name} 
			unless $companies{ $trunk->{company_name} }++;
		push @cities, $trunk->{city} 
			unless $companies{ $trunk->{city} }++;
		push @obls, $trunk->{oblast} 
			unless $companies{ $trunk->{oblast} }++;
		push @fos, $trunk->{fo} 
			unless $companies{ $trunk->{fo} }++;
		push @trunks, $trunk->{trunk} 
			unless $companies{ $trunk->{trunk} }++;
	}

	@companies = sort @companies;
	@cities = sort @cities;
	@obls = sort @obls;
	@fos = sort @fos;
	@trunks = sort @trunks;

	$c->stash->{json_data} = { 
		switches => \@switches,
		switch_types => \@switch_types,
		companies => \@companies,
		cities => \@cities,
		obls => \@obls,
		fos  => \@fos,
		trunks => \@trunks,
		selected => $selected
	};

	$c->component('View::JSON')->encoding('utf-8');
	$c->forward('View::JSON');
}
=head1 AUTHOR

A clever guy

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

__PACKAGE__->meta->make_immutable;

1;
